export default defineContentScript({
  matches: ['<all_urls>'],
  main() {
    let floatBtn: HTMLDivElement | null = null;
    let btn: HTMLButtonElement | null = null;
    let dialog: HTMLIFrameElement | null = null;
    let isDragging = false;
    let offsetX = 0;
    let offsetY = 0;

    // 预加载所有图标
    const preloadIcons = () => {
      const icons = [
        'icon/chat-icon.svg',
        'icon/user.svg',
        'vue.svg',
        'wxt.svg'
      ];
      icons.forEach(icon => {
        const img = new Image();
        img.src = chrome.runtime.getURL(icon);
      });
    };
    preloadIcons();

    // 创建浮动按钮
    function createFloatingButton() {
      // 创建浮动按钮容器
      floatBtn = document.createElement('div');
      floatBtn.style.position = 'fixed';
      floatBtn.style.bottom = '20px';
      floatBtn.style.right = '20px';
      floatBtn.style.zIndex = '9999';
      
      // 创建圆形图标按钮
      btn = document.createElement('button');
      const defaultIcon = document.createElement('img');
      defaultIcon.src = chrome.runtime.getURL('icon/chat-icon.svg');   
      defaultIcon.style.width = '48px';
      defaultIcon.style.height = '48px';
      defaultIcon.style.borderRadius = '50%';
      defaultIcon.style.objectFit = 'cover';
      // defaultIcon.alt = '对话图标';
      btn.appendChild(defaultIcon);
      
      btn.style.padding = '0';
      btn.style.background = 'transparent';
      btn.style.border = 'none';
      // btn.style.borderRadius = '50%';
      btn.style.cursor = 'pointer';
      btn.style.transition = 'transform 0.2s';
      btn.title = '点击对话';

      // 优化鼠标事件处理
      if (btn) {
        const handleMouseEnter = () => {
          if (btn?.firstChild) {
            (btn.firstChild as HTMLImageElement).src = 
              chrome.runtime.getURL('icon/user.svg');
            btn.style.transform = 'scale(1)';
          }
        };
        
        const handleMouseLeave = () => {
          if (btn?.firstChild && (!dialog || dialog.style.display === 'none')) {
            (btn.firstChild as HTMLImageElement).src = 
              chrome.runtime.getURL('icon/chat-icon.svg');
            btn.style.transform = 'scale(1)';
          }
        };
        
        btn.addEventListener('mouseenter', handleMouseEnter, { passive: true });
        btn.addEventListener('mouseleave', handleMouseLeave, { passive: true });
      }

    // 创建iframe聊天窗口
    const iframe = document.createElement('iframe');
    iframe.style.display = 'none';  // 初始设置为隐藏
    iframe.style.position = 'fixed';
    iframe.style.bottom = '80px';
    iframe.style.right = '20px';
    iframe.style.width = '400px';
    iframe.style.height = '600px';
    iframe.style.border = 'none';
    iframe.style.borderRadius = '12px';
    iframe.style.boxShadow = '0 0 15px rgba(0,0,0,0.2)';
    iframe.style.zIndex = '9998';
    iframe.allow = 'fullscreen;microphone';
    iframe.title = '聊天机器人';
    dialog = iframe;

    // 从storage获取chatbotUrl
    chrome.storage.sync.get(['chatbotUrl'], (result) => {
      if (!result.chatbotUrl) {
        console.warn('Chatbot URL is not configured');
        return;
      }

      if (dialog) {
        dialog.src = result.chatbotUrl;
      }
    });

      // 优化点击事件处理
      if (btn) {
        btn.addEventListener('click', () => {
          if (dialog && btn?.firstChild) {
            const isOpening = dialog.style.display === 'none';
            dialog.style.display = isOpening ? 'block' : 'none';
            (btn.firstChild as HTMLImageElement).src = 
              chrome.runtime.getURL(isOpening 
                ? 'icon/user.svg' 
                : 'icon/chat-icon.svg');
          }
        }, { passive: true });
      }

      // 添加拖动功能
      if (btn) {
        btn.addEventListener('mousedown', (e) => {
          if (!floatBtn || !btn) return;
          isDragging = true;
          offsetX = e.clientX - floatBtn.getBoundingClientRect().left;
          offsetY = e.clientY - floatBtn.getBoundingClientRect().top;
          btn.style.cursor = 'grabbing';
        }, { passive: true });
      }

      document.addEventListener('mousemove', (e) => {
        if (!isDragging || !floatBtn) return;
        floatBtn.style.left = `${e.clientX - offsetX}px`;
        floatBtn.style.top = `${e.clientY - offsetY}px`;
        floatBtn.style.right = 'auto';
        floatBtn.style.bottom = 'auto';
      }, { passive: true });

      document.addEventListener('mouseup', () => {
        isDragging = false;
        if (btn) btn.style.cursor = 'pointer';
      }, { passive: true });

      // 自适应窗口大小
      function resizeDialog() {
        if (dialog) {
          const width = Math.min(400, window.innerWidth * 0.8);
          const height = Math.min(600, window.innerHeight * 0.7);
          dialog.style.width = `${width}px`;
          dialog.style.height = `${height}px`;
        }
      }

      window.addEventListener('resize', resizeDialog, { passive: true });
      resizeDialog();
      
      // 添加到页面
      floatBtn.appendChild(btn);
      document.body.appendChild(floatBtn);
      document.body.appendChild(dialog);
    }

    // 移除浮动按钮
    function removeFloatingButton() {
      if (floatBtn && document.body.contains(floatBtn)) {
        document.body.removeChild(floatBtn);
      }
      if (dialog && document.body.contains(dialog)) {
        document.body.removeChild(dialog);
      }
    }

    // 初始化时创建按钮
    createFloatingButton();

    // 监听插件卸载事件
    return {
      onDestroy() {
        removeFloatingButton();
      }
    };
  },
});
